package com.mahjong.server.model;

import java.util.LinkedList;
import java.util.List;

import com.mahjong.server.common.EmPlayerStatus;
import com.mahjong.server.common.EmRoomStatus;
import com.mahjong.server.component.logic.manager.LogicManager;

/**
 * 房间类，对一个房间的玩家进行封装，以便各个玩家之间数据交互
 * 
 * @author Simple
 * @date 2013-3-13 下午04:15:51
 * @Description TODO
 */
public class Room {

	private int id;

	private List<Player> players = new LinkedList<Player>();// 玩家

	private String name;// 房间名

	private String password;// 房间密码

	private int playerCount;// 玩家人数

	private int totalCount = 4;// 总人数

	private EmRoomStatus status = EmRoomStatus.WAITING;// 房间状态

	public Room() {}
	
	public Room(int id) {
		this.id = id;
		init();
	}

	/**
	 * 初始化房间麻将数据
	 */
	private void init() {
		System.out.println("room init data");
		new LogicManager().init(this.id);
	}

	/**
	 * 房间添加玩家
	 * 
	 * @param p
	 * @return
	 */
	public boolean addPlayer(Player p) {
		if (playerCount < totalCount) {
			players.add(p);
			playerCount++;
			if (playerCount == totalCount) {
				status = EmRoomStatus.FULL;
			}
			p.setRoomId(id);
			p.setPosition(p.getPosition() + 1);
			p.setStatus(EmPlayerStatus.WAITING);
			return true;
		}
		return false;
	}

	/**
	 * 玩家退出房间
	 * 
	 * @param p
	 */
	public void removePlayer(Player p) {
		players.remove(p);
		playerCount--;
		status = EmRoomStatus.WAITING;
		p.setRoomId(-1);
		p.setPosition(-1);
		p.setStatus(EmPlayerStatus.FREE);
	}

	/**
	 * 开始游戏
	 * 
	 * @return
	 */
	public boolean startGame() {
		int readyCount = 0;
		for (Player player : players) {
			if (player.getStatus() == EmPlayerStatus.READY) {
				readyCount++;
			}
		}
		return readyCount == 4 ? true : false;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public List<Player> getPlayers() {
		return players;
	}

	public void setPlayers(List<Player> players) {
		this.players = players;
	}

	public int getPlayerCount() {
		return playerCount;
	}

	public void setPlayerCount(int playerCount) {
		this.playerCount = playerCount;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setStatus(EmRoomStatus status) {
		this.status = status;
	}

	public EmRoomStatus getStatus() {
		return status;
	}
}
